import sys

from PyQt5.QtCore import QStringListModel
from PyQt5.QtWidgets import QDialog, QApplication, QAbstractItemView

from DatabaseInteraction import DatabaseInteraction
from ui.SetRecognitionRangeFormUi import Ui_SetRecognizationRangeForm


class SetRecognitionRangeForm(QDialog):
    def __init__(self):
        super(SetRecognitionRangeForm, self).__init__()
        self.ui = Ui_SetRecognizationRangeForm()
        self.ui.setupUi(self)

        self.database_interaction = DatabaseInteraction()
        self.class_list = self.database_interaction.get_all_class()
        self.class_list_model = QStringListModel()

        self.select_list = self.database_interaction.get_selected_class()
        self.select_list_model = QStringListModel()

        self.init_ui_set()
        self.init_ui_connect()

    def init_ui_set(self):
        self.ui.allClassView.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.ui.selectedClassView.setEditTriggers(QAbstractItemView.NoEditTriggers)

    def init_ui_connect(self):
        self.class_list_model.setStringList(self.class_list)
        self.ui.allClassView.setModel(self.class_list_model)

        self.select_list_model.setStringList(self.select_list)
        self.ui.selectedClassView.setModel(self.select_list_model)

        self.ui.acceptButton.clicked.connect(self.accept_button)
        self.ui.rejectButton.clicked.connect(self.reject_button)
        self.ui.pushButton.clicked.connect(self.all_class_view_double_clicked)
        self.ui.removeButton.clicked.connect(self.select_class_view_double_clicked)

        self.ui.allClassView.doubleClicked.connect(self.all_class_view_double_clicked)
        self.ui.selectedClassView.doubleClicked.connect(self.select_class_view_double_clicked)

    def select_class_view_double_clicked(self):
        index = self.ui.selectedClassView.currentIndex()
        i = index.row()
        del self.select_list[i]
        self.select_list_model.setStringList((self.select_list))

    def all_class_view_double_clicked(self):
        index = self.ui.allClassView.currentIndex()
        i = index.row()
        select_class = self.class_list[i]
        if select_class not in self.select_list:
            self.select_list.append(select_class)
        self.select_list_model.setStringList(self.select_list)

    def accept_button(self):
        self.database_interaction.update_selected_class(self.select_list)
        print(self.database_interaction.get_selected_class())
        self.close()

    def reject_button(self):
        self.close()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    dialog = SetRecognitionRangeForm()
    dialog.show()
    app.exit(dialog.exec_())
